<%@ page import="com.devicemantra.coordinate.dataobjects.*,java.util.*,com.google.appengine.api.datastore.KeyFactory" %>
<html xmlns="http://www.w3.org/1999/xhtml">
 
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Add Locations !</title>
 <head>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">


 <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAZtqx8JxkReW-dJBlgM4IzBSWV9LTOb7Fazl1VdNawM1J6KSITRQSexRo0YWXBwuD4djbVUg8Tnmjow"
            type="text/javascript"></script>
<script type="text/javascript" src="/js/jquery.js"></script> 
<script type="text/javascript" src="/js/jquery.corner.js"></script> 
<script type="text/javascript" src="/js/xmlhelper.js"></script> 
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js"></script> 

<script type="text/javascript">

    var map;
    var lTime = 0;
    var g_marker_manager;
    var g_geoclient_coder;
    var g_dragged_marker;
    

    /* Added by Amith for poly feature */
    var g_marker_arr = new Array();
    var poly;
	var count = 0;
	var points = new Array();
	var markers = new Array();
	var icon_url ="http://labs.google.com/ridefinder/images/";
	var tooltip;
	var lineColor = "#0000af";
	var fillColor = "#335599";
	var lineWeight = 3;
	var lineOpacity = .8;
	var fillOpacity = .2;

function tryThisOne()
{
	if (document.getElementById('lat').value == "")
	{
             alert('Please enter the Username');
	     return;
	}

       if(document.getElementById('long').value == "")
	{
             alert('Please enter the Password');
	     return;
	}

       var httpPostReq = initXMLHttpClient();

       if(!httpPostReq)
       {
            alert('We are Sorry, you need an AJAX Compliant browser to use this page !');
	    return;
       }

       var selObj = document.getElementById('states');
       var selIndex = selObj.selectedIndex;

 
       if(selObj.options[selIndex].text == "" ||
	  selObj.options[selIndex].text == "Select state" )
       {
	       alert("Please select a state");
	       return;
       } 


       var url = "/coordinate/php/save_info.php";
       var params = "lat="+document.getElementById('lat').value+"&long="+document.getElementById('long').value +
	       "&state="+selObj.options[selIndex].text;

       /*clear our update tag*/
       document.all.update_result.innerHTML="";
       httpPostReq.open("POST",url,true);

       httpPostReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
       httpPostReq.setRequestHeader("Content-length", params.length);
       httpPostReq.setRequestHeader("Connection", "close");

       httpPostReq.onreadystatechange = function()
       {
	      
       if(httpPostReq.readyState == 4 && httpPostReq.status == 200)
       {

	     document.all.update_result.innerHTML="<font color=brown size=3>"+httpPostReq.responseText+"</font>";
       }
	    
	      
       }
        
      httpPostReq.send(params);

}


 function initXMLHttpClient() {
     var xmlhttp;
     try {
         // Mozilla / Safari / IE7
         xmlhttp = new XMLHttpRequest();
     } catch (e) {
          // IE
          var XMLHTTP_IDS = new Array('MSXML2.XMLHTTP.5.0',
                                     'MSXML2.XMLHTTP.4.0',
                                     'MSXML2.XMLHTTP.3.0',
                                     'MSXML2.XMLHTTP',
                                     'Microsoft.XMLHTTP' );
        var success = false;
          for (var i=0;i < XMLHTTP_IDS.length && !success; i++) {
              try {
                   xmlhttp = new ActiveXObject(XMLHTTP_IDS[i]);
                      success = true;
                } catch (e) {}
          }
          if (!success) {
              throw new Error('Unable to create XMLHttpRequest.');
          }
     }
     return xmlhttp;
 }


function getStatesData()
{
	var httpGetReq = initXMLHttpClient();
        httpGetReq.onreadystatechange =function() {
	if (httpGetReq.readyState == 4) 
	{
		if (httpGetReq.status==200)
		{
			var lXmlDoc = loadXmlText(httpGetReq.responseText);


			if(lXmlDoc)
			{
				var lNodeList = xmlDoc.getElementsByTagName("state");
			

				parseXmlData(lNodeList);
			}
			else
	                {
                           alert('XML parsing FAILURE!');
			}
		}
        }
	}
  
       
        httpGetReq.open("GET","/coordinate/php/get_all_states_data.php",true);
        httpGetReq.send(null); 

}









function isSet(pVar)
{
	alert(typeof pVar);
}


function parseXmlData(pNodeList)
{
  var lStateList = pNodeList;
  var i=0;
  var lTempNode;
  var lNode;
  var lStateName;
  var lCapital;
  var lLat;
  var lLongi;
  var lMarker;
  var lMarkerArr = [];
  var lHtml;


  for( ;i<lStateList.length;i++)
  {
       
	  lTempNode = lStateList[i];
	  lNode = lTempNode.getElementsByTagName("STATE_NAME");
          lStateName = (lNode[0].childNodes[0]).nodeValue; 
	  lNode = lTempNode.getElementsByTagName("STATE_CAPITAL");
	  lCapital= (lNode[0].childNodes[0]).nodeValue; 
	  lNode = lTempNode.getElementsByTagName("LAT");
	  lLat = (lNode[0].childNodes[0]).nodeValue; 
	  lNode = lTempNode.getElementsByTagName("LONGI");
	  lLongi = (lNode[0].childNodes[0]).nodeValue; 
	  lMarker = new GMarker(new GLatLng(lLat,lLongi),{draggable: false});
	 /* GEvent.addListener(lMarker,"click",function(){
		  alert(lHtml); 
		  lMarker.openInfoWindowHtml(lHtml);		   
  });*/
	  lHtml = "<html><body bgcolor=\"lightbrown\"><table>" +
		   "<tr><td> State : " + lStateName + "</td></tr>" +
		   "<tr><td><font color=black> Capital : " + lCapital + "</font></td></tr>"+
		   "</table></body></html> ";

	  lMarker.bindInfoWindowHtml(lHtml);
	  lMarkerArr[i] = lMarker; 
  }

  g_marker_manager.addMarkers(lMarkerArr,0,15);
  g_marker_manager.refresh(lMarkerArr);
}


function showMarker()
{

}

function clearMarkers()
{
	g_marker_manager.clearMarkers();
	//alert(map.getZoom()); 
	//getStatesData();
	//load();
	/*var points =
		[
		new GLatLng(24.947215,55.074463),
		new GLatLng(24.278014,55.030518),
		new GLatLng(24.328078,55.744629)
		
		];
		var polyline = new GPolyline(points,'#FF0000',3,0.4);
		map.addOverlay(polyline);
		alert("testing");
		polyline.insertVertex(4,new GLatLng(21.947215,55.074463));
		polyline.insertVertex(4,new GLatLng(24.947215,55.074463)); */
		
		
}


/*******************************************************
*  GEO CODER functions
********************************************************/
function OnDragStart(latlng) 
{

   
}


function OnDragEnd(latlng) {
 

  if (latlng != null) {
    address = latlng;
    g_geoclient_coder.getLocations(latlng, showAddress);
  }
}



function getAddress(overlay, latlng) {
//alert("get address called"); 
if(g_dragged_marker !=null)
{
	if (latlng != null)  
    {
      address = latlng;
      g_geoclient_coder.getLocations(latlng, showAddress);
    }
}
}


function isDefined(pObj)
{
	var lIsSet = true;
	if(typeof(pObj) == 'undefined')
	{
		   //alert("It is undefined ");
		  lIsSet = false;
	}
	return lIsSet;
}

function getEmirate(jsonobj,index)
{
	var lEmirate = "N/A";
	if(isDefined(jsonobj.Placemark[index]))
	{
	//alert("1");
	if(isDefined(jsonobj.Placemark[index].AddressDetails))
	{
		//alert("2");
		if(isDefined(jsonobj.Placemark[index].AddressDetails.Country))
		{
			//alert("3");
			if(isDefined(jsonobj.Placemark[index].AddressDetails.Country.AdministrativeArea))
			{
				//alert("4");
				lEmirate = jsonobj.Placemark[index].AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
			}	
		}
	  }		
	}
	return lEmirate; 
}

function getThoroughFareName(jsonobj,index)
{
	var lTname = "N/A";
	if(isDefined(jsonobj.Placemark[index]))
	{ 
	//alert("1");
	if(isDefined(jsonobj.Placemark[index].AddressDetails))
	{
		//alert("2");
		if(isDefined(jsonobj.Placemark[index].AddressDetails.Country))
		{
			//alert("3");
			if(isDefined(jsonobj.Placemark[index].AddressDetails.Country.AdministrativeArea))
			{
				//alert("4");
				if(isDefined(jsonobj.Placemark[index].AddressDetails.Country.AdministrativeArea.Locality))
				{
					//alert("5");
					if(isDefined(jsonobj.Placemark[index].AddressDetails.Country.AdministrativeArea.Locality.DependentLocality))
					{
						if(isDefined(jsonobj.Placemark[index].AddressDetails.Country.AdministrativeArea.Locality.DependentLocality.Thoroughfare))
						{
							//alert("7");
							//alert("ThoroughfareName is " + jsonobj.Placemark[index].AddressDetails.Country.AdministrativeArea.Locality.DependentLocality.Thoroughfare.ThoroughfareName);
							lTname =  jsonobj.Placemark[index].AddressDetails.Country.AdministrativeArea.Locality.DependentLocality.Thoroughfare.ThoroughfareName;
							
						}
					}
					else if(isDefined(jsonobj.Placemark[index].AddressDetails.Country.AdministrativeArea.Locality.Thoroughfare))
					{
						//alert("entering else if ");
						//alert("jsonobj.Placemark[index].AddressDetails.Country.AdministrativeArea.Locality.Thoroughfare");
						//alert("ThoroughfareName is " + jsonobj.Placemark[index].AddressDetails.Country.AdministrativeArea.Locality.Thoroughfare.ThoroughfareName);
						lTname =  jsonobj.Placemark[index].AddressDetails.Country.AdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
						
					}
				}
			}
		}
	  }		
	}
	return lTname; 
}



function getDependentLocality(jsonobj,index)
{
	var lDepLoc = "N/A";
	if(isDefined(jsonobj.Placemark[index]))
	{
	//alert("1");
	if(isDefined(jsonobj.Placemark[index].AddressDetails))
	{
		//alert("2");
		if(isDefined(jsonobj.Placemark[index].AddressDetails.Country))
		{
			//alert("3");
			if(isDefined(jsonobj.Placemark[index].AddressDetails.Country.AdministrativeArea))
			{
				//alert("4");
				if(isDefined(jsonobj.Placemark[index].AddressDetails.Country.AdministrativeArea.Locality))
				{
					//alert("5");
					if(isDefined(jsonobj.Placemark[index].AddressDetails.Country.AdministrativeArea.Locality.DependentLocality))
					{
						//alert("6");
						//alert("DependentLocality is " + jsonobj.Placemark[index].AddressDetails.Country.AdministrativeArea.Locality.DependentLocality.DependentLocalityName);
						lDepLoc =  jsonobj.Placemark[index].AddressDetails.Country.AdministrativeArea.Locality.DependentLocality.DependentLocalityName;
					}
					else
					{
						lDepLoc = jsonobj.Placemark[index].AddressDetails.Country.AdministrativeArea.Locality.LocalityName;
					}
				}
				
			}
		}
	  }		
	}
	return lDepLoc; 
}

function getThoroughFareNameAsAddressLine(jsonobj,index)
{
	var lDepLoc = "N/A";
	//alert("1");
	if(isDefined(jsonobj.Placemark[index].AddressDetails))
	{
		//alert("2");
		if(isDefined(jsonobj.Placemark[index].AddressDetails.Country))
		{
			//alert("3");
			if(isDefined(jsonobj.Placemark[index].AddressDetails.Country.AdministrativeArea))
			{
				//alert("4");
				if(isDefined(jsonobj.Placemark[index].AddressDetails.Country.AdministrativeArea.Locality))
				{
					//alert("5");
					if(isDefined(jsonobj.Placemark[index].AddressDetails.Country.AdministrativeArea.Locality.DependentLocality))
					{
						//alert("6");
						//alert("DependentLocality is " + jsonobj.Placemark[index].AddressDetails.Country.AdministrativeArea.Locality.DependentLocality.DependentLocalityName);
						lDepLoc =  jsonobj.Placemark[index].AddressDetails.Country.AdministrativeArea.Locality.DependentLocality.AddressLine[0];
					}
				}
			}
		}
			
	}
	return lDepLoc; 
}

 
function showAddress(response) 
{ 


	if(g_dragged_marker != null)
	{	
 	  if (!response || response.Status.code != 200) 
	  {
		  alert("Error Status Code:" + response.Status.code);
		  g_dragged_marker.bindInfoWindowHtml(null);
		  g_dragged_marker.bindInfoWindowHtml("<font color=red size=2> SORRY, problem retrieving location information from Google.com :-( </font>");

	  } 
	  else  
	  {
    		//alert("Status Code:" + response.Status.code);
    	// alert(response.responseText);
    	var lDepLoc = "";
    	var lTName = "";
    	var lEmirate = "";
    	var jsonobj = eval(response);
    	lDepLoc = getDependentLocality(jsonobj,0);
    	lTName = getThoroughFareName(jsonobj,0);
    	lEmirate = getEmirate(jsonobj,0);
    	if( lDepLoc == "N/A")
    		lDepLoc = getDependentLocality(jsonobj,1);

    	if( lTName == "N/A")
    	{
        	//alert("Getting tname 2nd time");
    		lTName = getThoroughFareNameAsAddressLine(jsonobj,0);
    	}

		
    	//alert(lDepLoc + "-" + lTName);
    	place = response.Placemark[0];
    	point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
	    
	   var l = g_dragged_marker.getLatLng();
	   //alert(g_dragged_marker.coord_name);
	   
	  // alert(place.AddressDetails.Country.AdministrativeArea);
	  // alert(place.AddressDetails.Country.AdministrativeArea.Locality.DependentLocality.DependentLocalityName); 
	  // var lValue = place.AddressDetails.Country.AdministrativeArea.Locality.DependentLocality.Thoroughfare.ThoroughfareName;
	  /* alert(jsonobj.Placemark[0].address);
	   */

	   /* We will format the address to be shown to the user based on whether the 
	      we got information from geo_coder or not */
	      var lAddressRow;  
		  if( (lDepLoc == "N/A" ) && (lTName == "N/A"))
		  {
			   lAddressRow = "<tr><td>Address:</td><input type=text name=address value=\"Please enter the Address\"" +  "</td></tr>";   
		  }
		  else if( (lDepLoc == "N/A") )
		  {
			   lAddressRow = "<tr><td>Address:</td><input type=text name=address value=\""+  lTName +  "\"" +  " READONLY  \"></td>";  
		  }else if( (lTName == "N/A") )
		  {
			  lAddressRow = "<tr><td>Address:</td><input type=text name=address value=\""+  lDepLoc +  "\"" +  " READONLY  \"></td>";
		  }else // lTname and lDepLoc are good 
		  {
			  lAddressRow = "<tr><td>Address:</td><input type=text name=address value=\""+ lDepLoc + ", " + lTName +  "\"" +  " READONLY  \"></td>";
			  //lAddressRow = "<tr><td>Address:</td><p>" + lDepLoc + ", " + lTName +  "</p></td>";
		  } 
	       
       
             var lTabbedInfoWindow = [];
  lTabbedInfoWindow[0] = new GInfoWindowTab("Add","<form name=saveLoc method=POST action=/coordinate/php/save_loc_to_db.php>" +
						  	    "<table>" +
						  	    "<tr><td><img src=" + g_dragged_marker.logoPath + "></td><td><font color=black><h3>Add Frame </h3></font></td></tr>" + 
							    "<tr><td>Department</td><input type=text name=dept_name value=\"" + g_dragged_marker.coord_name + "\"" +  " READONLY ></td>" +
							    "<tr><td>Emirate:</td><input type=text name=emirate value=\""+ lEmirate + "\"" +  " READONLY  \"></td>" +
							    lAddressRow +   
							    "<tr><td>Latitude :</td><td><input type=text name=lat value="+l.lat()+"></td></tr>" +
							    "<tr><td>Longitude :</td><td><input type=text name=lon value="+l.lng()+"></td></tr>" +
							    "<tr><td>Location Description :</td><input type=text name=loc_desc></td>" +
							    "<tr><td><input type=hidden name=loc_type_id value="+g_dragged_marker.loc_type_id+"><input type=button value=Save onClick=saveLocFormToDb()></td>" +
	   "<tr><td><div id=save_loc_status></div></td></tr>" +
							    "</table>" + "</form>");
	    /*lTabbedInfoWindow[1] = new GInfoWindowTab("Flash","<form name=saveMessage method=POST action=/coordinate/php/save_loc_to_db.php>" +
		  	    "<table>" +
		  	  "<tr><td><img src=" + g_dragged_marker.logoPath + ">" +  
		  	  	"  Send a Message</td></tr>" + 
		  	    "<br><TEXTAREA name=comments rows=4 cols=20></TEXTAREA></td></tr>" +
		  	    "<tr><td><br><input type=button value=Flash onClick=saveMessageToDb()></tr></td>" +  
		  	    "</table>" + "</form>"); */
	   // lTabbedInfoWindow[2] = new GInfoWindowTab("Modify","<font size=2 color=black>Save Info. </font>");
	      
    	      g_dragged_marker.bindInfoWindowTabs(null);
    	      g_dragged_marker.bindInfoWindowTabs(lTabbedInfoWindow);
   	  // g_dragged_marker = null; 
  	  }
        }
}
   


    function load() 
    {

      if (GBrowserIsCompatible()) 
      {
        map = new GMap2(document.getElementById("map"));
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		map.enableGoogleBar();

		var center = new GLatLng(25.075648445630527,55.61279296875);
        map.setCenter(center,5);
        map.setZoom(8);
		g_geoclient_coder = new GClientGeocoder();
		g_geoclient_coder.setBaseCountryCode("ae");

        var mgrOptions = { borderPadding: 0, maxZoom: 15, trackMarkers: true };
		g_marker_manager = new MarkerManager(map,mgrOptions);
        //GEvent.addListener(map, "click", getAddress);

		GEvent.addListener(map, "click", leftBtnClick);
        
    	// Add a div element for toolips
    	 tooltip = document.createElement("div");
    	 tooltip.className="tooltip";
    	 map.getPane(G_MAP_MARKER_PANE).appendChild(tooltip);
	
      }

     
      //Rounded("div#coordinate","tl tr","#ffffff","#a4f4a0","smooth");
      //Rounded("div#nifty","bl br","#ffffff","#a4f4a0","smooth");
      //Nifty("div#about li","tl bottom big fixed-height");
      
      
    }



    /*****************************************************************
     panToPlaceAndAddMarker()
     *****************************************************************/
     function
     panToPlaceAndAddMarker(pLat,pLng,pPlaceName,pUserPhotoUrl)
     {
         var lPoint = new GLatLng(pLat,pLng);
       
         //alert(pUserPhotoUrl);
                   
         map.panTo(lPoint);
         var marker = new GMarker(lPoint);
         map.addOverlay(marker);
         
	
         

         //document.getElementById('user_info').innerHTML  = '<img width=100 height=100 src=http://lwn.net/images/conf/ols+ks2005/linus-fun.jpg>';
          document.getElementById('user_info').innerHTML = pUserPhotoUrl;
          
     }

function onBtnClick(pClickedId)
{
  var lRowImg = document.getElementById(pClickedId);
 // alert(pClickedId + " the src = " + lRowImg.src + " Width : " + lRowImg.width);

  var Icon = new GIcon();
  Icon.image = lRowImg.src ;
  Icon.iconSize = new GSize(lRowImg.width, lRowImg.height);
  //Icon.shadow = "myshadow.png";
  //Icon.shadowSize = new GSize(36, 34);
  Icon.iconAnchor = new GPoint(5, 34);
  Icon.infoWindowAnchor = new GPoint(5, 2);


  var marker = new GMarker(map.getCenter(),{icon: Icon,draggable: true});
  GMarker.prototype.setMarkerLogo = setLogo;
  marker.setMarkerLogo(lRowImg.src);
  marker.coord_name = pClickedId;
  marker.loc_type_id = lRowImg.name;

  GEvent.addListener(marker,"dragstart",function() {
  
	  g_dragged_marker = marker;
	  //alert(g_dragged_marker);
  })
  GEvent.addListener(marker,"dragend",OnDragEnd);

    

  /*var lTabbedInfoWindow = [];
  lTabbedInfoWindow[0] = new GInfoWindowTab("Save ","<form name=saveLoc method=POST action=save_loc.php>" +
	  	    "<table>" +
		    "<tr colspan=1><td><img src=" + marker.logoPath + "></td></tr>" + 
		    "<tr><td>State:</td><input type=text name=loc_desc value=UnKnown></td>" +
		    "<tr><td>Location Description :</td><input type=text name=state_save_form></td>" +
		    "</table>" +
                    "</form>");
  
  lTabbedInfoWindow[1] = new GInfoWindowTab("Modify","<font size=2 color=black>Save Info. </font>");

  marker.bindInfoWindowTabs(lTabbedInfoWindow);*/

  g_dragged_marker = marker;
  OnDragEnd(map.getCenter());
  g_marker_manager.addMarker(marker,0,15);
  g_marker_manager.refresh();
  
}

function setLogo(pLogoPath)
{
	//alert("set marker " + pLogoPath);
	this.logoPath = pLogoPath;
}

function getValueFromNode(pNode)
{
	return (pNode[0].childNodes[0]).nodeValue; 
}

function showFramesOnMap(pNodeList)
{
	  for(index =0; index < pNodeList.length ; index++)
	  {
		   var lTempNode = pNodeList[index];
		   var lNode = lTempNode.getElementsByTagName("CFrameId");
		   var lFrameId = getValueFromNode(lNode);
		   //alert(lFrameId);
		   lNode = lTempNode.getElementsByTagName("CLat");
		   var lLat = getValueFromNode(lNode);
		   //alert(lLat);
		   lNode = lTempNode.getElementsByTagName("CLong");
		   var lLong = getValueFromNode(lNode);
		   //alert(lLong);
		   lNode = lTempNode.getElementsByTagName("CEmirate");
		   var lEmirate = getValueFromNode(lNode);
		   //alert(lEmirate);
		   lNode = lTempNode.getElementsByTagName("CAddress");
		   var lAddress = getValueFromNode(lNode);
		   //alert(lAddress);
		   lNode = lTempNode.getElementsByTagName("CDepartment");
		   var lDept = getValueFromNode(lNode);
		   //alert(lDept);
		   lNode = lTempNode.getElementsByTagName("CDepartmentLogo");
		   var lDeptLogo = getValueFromNode(lNode);
		   //alert(lDeptLogo);
		   lNode = lTempNode.getElementsByTagName("CDescription");
		   var lDesc = getValueFromNode(lNode);
		   //alert(lDesc);
		   //alert(lFrameId + "" + lLat + " " + lLong + " " + lEmirate + " " + lAddress + " " + lDept + " " + lDesc);
		   /* Add the marked on the coordinates */
		   //lMarker = new GMarker(new GLatLng(lLat,lLong),{draggable: false});
		   //g_marker_manager.addMarker(lMarker,0,15);

		   var Icon = new GIcon();
		   Icon.image = lDeptLogo ;
		   Icon.iconSize = new GSize(21,31);
		   //Icon.shadow = "myshadow.png";
		   //Icon.shadowSize = new GSize(36, 34);
		   Icon.iconAnchor = new GPoint(5, 34);
		   Icon.infoWindowAnchor = new GPoint(5, 2); 

		   var lLatLong = new GLatLng(lLat,lLong);
		   var lMarker = new GMarker(lLatLong,{icon: Icon,draggable: false});
		   GMarker.prototype.setMarkerLogo = setLogo;
		   lMarker.setMarkerLogo(lDeptLogo);

		    
		   lMarker.frame_id = lFrameId;
		   lMarker.department = lDept;
		   lMarker.logo_path = lDeptLogo;
		   lMarker.latitude = lLat;
		   lMarker.longitude = lLong;
		   lMarker.emirate = lEmirate;
		   lMarker.address = lAddress;
		   lMarker.description = lDesc;
		   lMarker.latLong = lLatLong;
		    	
		   GEvent.addListener(lMarker,"click",cb_marker_clicked);
		   g_marker_arr.push(lMarker);
		   g_marker_manager.addMarker(lMarker,0,15);
		   g_marker_manager.refresh(); 

		   
	}
	  

	  /*lMarker = new GMarker(new GLatLng(lLat,lLongi),{draggable: false});
	  g_marker_manager.addMarker(lMarker,0,15);
	  lMarker.bindInfoWindowHtml("<table>" +
		                     "<tr><td>State Name:</td><td>"+lStateName+"</td></tr>" +
	                             "<tr><td>Capital</td><td>"+lCapital+"</td></tr>" +
				     "</table>" ); 

	  lLatLng = new GLatLng(lLat,lLongi);
	  map.setCenter(lLatLng, 10 ); */



}

function saveLocFormToDb()
{
       var httpPostReq = initXMLHttpClient();


       /*Erro checking, check whether all the fields are valid
	 for us to submit*/

       document.getElementById('save_loc_status').innerHTML = "<font> Processing.....</font>";
       if(!httpPostReq)
       {
            alert('We are Sorry, you need an AJAX Compliant browser to use this page !');
	    return;
       }

       var url = "/AddFrame";
       var params = "dept_name="+document.forms['saveLoc'].dept_name.value+
       			    "&lat="+document.forms['saveLoc'].lat.value + 
       			    "&lon="+document.forms['saveLoc'].lon.value + 
       			 	"&address="+document.forms['saveLoc'].address.value + 
       			    "&frame_desc="+document.forms['saveLoc'].loc_desc.value + 
       			 	"&emirate="+document.forms['saveLoc'].emirate.value;
		     
       httpPostReq.open("POST",url,true);

       httpPostReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
       httpPostReq.setRequestHeader("Content-length", params.length);
       httpPostReq.setRequestHeader("Connection", "close");

       httpPostReq.onreadystatechange = function()
       {
	       if(httpPostReq.readyState == 4 && httpPostReq.status == 200)
	       {
		       
               alert(   httpPostReq.responseText );     
		       if( httpPostReq.responseText != "Success")
		       {
			      
			  document.getElementById('save_loc_status').innerHTML = "<img src=\"/icons/ok.png\" />" + " Frame added";
			  document.getElementById('frame_add_status').innerHTML = "<img height=32 width=32 src=\"/icons/info.png\" /> Frame id<br>" +  "<div style=\"font-family:verdana font-size:6\"> " + httpPostReq.responseText + "</div>" ;          
			  g_dragged_marker.disableDragging();
			  
		       }
		       else
		       {
                         alert('<font color=red><b>Failure adding Location !</b></font>');
		       }
	       }
	    
	      
       }
       document.getElementById('save_loc_status').innerHTML = "Processing..";  
      httpPostReq.send(params);

}



function saveMessageToDb()
{

	var httpPostReq = initXMLHttpClient();
	/*Erro checking, check whether all the fields are valid
	for us to submit*/

	document.getElementById('msg_send_status').innerHTML = "<font> Processing.....</font>";
	if(!httpPostReq)
	{
     	alert('We are Sorry, you need an AJAX Compliant browser to use this page !');
 		return;
	}

	var url = "/ProcessMessage";
	var params = "cmessage="+document.forms['saveMessage'].message.value+
			    "&cframe_id="+document.forms['saveMessage'].frame_id.value;
	     
	httpPostReq.open("POST",url,true);

	httpPostReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	httpPostReq.setRequestHeader("Content-length", params.length);
	httpPostReq.setRequestHeader("Connection", "close");

	httpPostReq.onreadystatechange = function()
	{
    	if(httpPostReq.readyState == 4 && httpPostReq.status == 200)
    {
	       
        //alert(   httpPostReq.responseText );     
	       if( httpPostReq.responseText != "Success")
	       {
		      
		  document.getElementById('msg_send_status').innerHTML = "<img height=32 width=32 src=\"/icons/ok.png\" />" +   " Message sent !" ;
		  //document.getElementById('frame_add_status').innerHTML = "<img height=32 width=32 src=\"/icons/info.png\" /> Frame id<br>" +  "<div style=\"font-family:verdana font-size:6\"> " + httpPostReq.responseText + "</div>" ;          
		  g_dragged_marker.disableDragging();
	       }
	       else
	       {
                  alert('<font color=red><b>Failure adding Location !</b></font>');
	       }
    }
 
   
	}
 
	httpPostReq.send(params);
}

function fakeMessageSent()
{
	document.getElementById('faked_message').innerHTML = "<font> Processing.....</font>";
	document.getElementById('faked_message').innerHTML = "<img height=32 width=32 src=\"/icons/ok.png\" />" +   " Contact added.";
}


function cb_marker_clicked()
{
	/*alert("click called now");
	alert("Testing marker"); */
	/*alert(this.department);
	alert(this.frame_id); 	*/

	var lTabbedInfoWindow = [];
	lTabbedInfoWindow[2] = new GInfoWindowTab("Info","<form name=saveLoc method=POST action=/coordinate/php/save_loc_to_db.php>" +
							  	    "<table>" +
							  	    "<tr><td><img src=" + this.logo_path + "></td><td><font color=black><h4>Location Info </h4></font></td></tr>" + 
								    "<tr><td>Department</td><input type=text name=dept_name value=\"" + this.department  + "\"" +  " READONLY ></td>" +
								    "<tr><td>Emirate:</td><input type=text name=emirate value=\""+ this.emirate + "\"" +  " READONLY  \"></td>" +
								    "<tr><td>Address:</td><input type=text name=address value=\""+  this.address +  "\"" +  " READONLY  \"></td>" +  
								    "<tr><td>Latitude :</td><td><input type=text name=lat value="+ this.latitude +" READONLY  ></td></tr>" +
								    "<tr><td>Longitude :</td><td><input type=text name=lon value="+ this.longitude +" READONLY  ></td></tr>" +
								    "<tr><td>Location Description :</td><input type=text name=loc_desc value=\"" + this.description  + "\" READONLY  ></td>" +
								    "<tr><td><input type=hidden name=cframe_id value="+ this.frame_id  +">" +
								    "<tr><td><p>" + this.frame_id  + "</p></td></tr>" +
		   							"<tr><td><div id=save_loc_status></div></td></tr>" +
								    "</table>" + "</form>"); 

	 lTabbedInfoWindow[0] = new GInfoWindowTab("Flash","<form name=saveMessage method=POST action=/coordinate/php/save_loc_to_db.php>" +
			  	    "<table>" +
			  	  "<tr><td><img src=" + this.logo_path + ">" +  
			  	  	"  Send a Message</td></tr>" + 
			  	    "<br><TEXTAREA name=message rows=3 cols=30></TEXTAREA></td></tr>" +
			  	    "<input type=hidden name=frame_id value="+ this.frame_id + ">" + 
			  	    "<tr><td><div id=msg_send_status></div></td></tr>" +
			  	    "<tr><td><br><input type=button value=Flash onClick=saveMessageToDb()></tr></td>" +  
			  	    "</table>" + "</form>"); 

	 lTabbedInfoWindow[1] = new GInfoWindowTab("Add Contacts","<form name=saveMessage method=POST action=/coordinate/php/save_loc_to_db.php>" +
		  	    "<table>" +
		  	  "<tr><td><img src=\"/images/add.png\" >" +  
		  	  	"<font size=3 color=#0E36B4><b> Add a Contact to this Location</font></b></td></tr>" + 
		  	    "<tr><td><font size=2 color=#7D7476>Name</font></td><td><input type=text  ></td></tr>" +
		  	  	"<tr><td><font size=2 color=#7D7476>Designation</font></td><td><input type=text  ></td></tr>" +
		  		"<tr><td><font size=2 color=#7D7476>Email</font></td><td><input type=text  ></td></tr>" +
		  		"<tr><td><font size=2 color=#7D7476>Mobile</font></td><td><input type=text  ></td></tr>" +
		  		"<tr><td><font size=2 color=#7D7476>Office Phone</font></td><td><input type=text  ></td></tr>" +
		  		"<tr><td><br><input type=button value=\"Add Contact\" onClick=fakeMessageSent()></tr></td>" +
		  		"<div id=\"faked_message\"></div>" +  
		  	    "</table>" + "</form>"); 
	 
		   // lTabbedInfoWindow[2] = new GInfoWindowTab("Modify","<font size=2 color=black>Save Info. </font>");
		      
	    	      //this.bindInfoWindowTabs(null);
	    	      //this.bindInfoWindowTabs(lTabbedInfoWindow);
	    	      this.openInfoWindowTabs(lTabbedInfoWindow);
				  return;
	   
}



function getFramesForDepartment()
{
	var lSelBox = document.getElementById('dept_combo_box');
	var lSelDept = lSelBox.options[lSelBox.selectedIndex].value;
	var lCheckBox = document.getElementById('showlocationsbox');
	var lIsShowAll = lCheckBox.checked;
    var httpGetReq = initXMLHttpClient();

    httpGetReq.onreadystatechange =function() 
    {
	   if (httpGetReq.readyState == 4) 
	   {
			if (httpGetReq.status==200)
			{
				//alert(httpGetReq.responseText);
				//alert(lIsShowAll);
				/* Clear all CFrames if the user does not want to see all of them */
				if(lIsShowAll == false)
					clearMarkers();
				
				
		  		var lXmlDoc = loadXmlText(httpGetReq.responseText);
		  		if(lXmlDoc)
		  		{
					var lNodeList = xmlDoc.getElementsByTagName("CLocation");
					//alert("node list length" + lNodeList.length);
					showFramesOnMap(lNodeList);
					document.getElementById('frame_add_status').innerHTML = "Done";
					//alert("We have a " + lNodeList.length + " Node LIST !");
					
	 			}
				else
				{
	                           alert('XML parsing FAILURE!');
		  		}
			}
	     }
	 }

     document.getElementById('frame_add_status').innerHTML = "<img height=32 width=32 src=\"/images/loading1.gif\"  alt=\"Loading..\" />"; 
	 httpGetReq.open("GET","/GetFrames?dept_name="+lSelDept,true);
	 httpGetReq.send(null);  
}

function getMapForState()
{
   
   var lSelBox = document.getElementById('states_box');
   var lSelState = lSelBox.options[lSelBox.selectedIndex].value;

    
   var httpGetReq = initXMLHttpClient();
   httpGetReq.onreadystatechange =function() {
	   

   if (httpGetReq.readyState == 4) 
   {
	if (httpGetReq.status==200)
	{
	  var lXmlDoc = loadXmlText(httpGetReq.responseText);

	  if(lXmlDoc)
	  {

		var lNodeList = xmlDoc.getElementsByTagName("state");
          
				if(lNodeList.length == 1)
				{

				  showStateOnMap(lNodeList);
				}
				else
				{
                                  alert("We have a " + lNodeList.length + "Node LIST !");
				}
	  }
	  else
	  {
                           alert('XML parsing FAILURE!');
	  }
	}
     }
     }
  
       
        httpGetReq.open("GET","/coordinate/php/get_states_data.php?state_id="+lSelState,true);
        httpGetReq.send(null); 
 
}

function showStateOnMap(pNodeList)
{
	var lTempNode = pNodeList[0];

	  lNode = lTempNode.getElementsByTagName("STATE_NAME");
	  lStateName = (lNode[0].childNodes[0]).nodeValue; 
	  lNode = lTempNode.getElementsByTagName("STATE_CAPITAL");
	  lCapital= (lNode[0].childNodes[0]).nodeValue; 
	  lNode = lTempNode.getElementsByTagName("LAT");
	  lLat = (lNode[0].childNodes[0]).nodeValue; 
	  lNode = lTempNode.getElementsByTagName("LONGI");
	  lLongi = (lNode[0].childNodes[0]).nodeValue; 
	  lMarker = new GMarker(new GLatLng(lLat,lLongi),{draggable: false});
	  g_marker_manager.addMarker(lMarker,0,15);
	  lMarker.bindInfoWindowHtml("<table>" +
		                     "<tr><td>State Name:</td><td>"+lStateName+"</td></tr>" +
	                             "<tr><td>Capital</td><td>"+lCapital+"</td></tr>" +
				     "</table>" ); 

	  lLatLng = new GLatLng(lLat,lLongi);
	  map.setCenter(lLatLng, 10 );



}
    
</script>
<style type="text/css">
.box {
background-color :#E2E2E2;
margin:15px;
padding:5px;
}
</style> 

<script>
$(document).ready(
function () 
{
	//alert("markers rounding function called");
	$("div.box").corner(); 
	$("#map").corner("bevel 4px");
	//$("#myscroll").fadeIn(3000);
	//$("#box1").fadeIn(3000);
}
);
</script>

<script type="text/javascript">
/* Added by Amith for poly feature */
function leftBtnClick(overlay,point)
{
	//alert("leftBtnClick called  now ");
	if(point) 
	{
		  count++;

		if(count%2 != 0) 
		{

		  	// Light blue marker icons
		  	var icon = new GIcon();
		  	icon.image = "http://www.wolfpil.de/lightblue.png";
		  	addIcon(icon);
		 }
		 else 
		 {
		  	// Purple marker icons
		  	var icon = new GIcon();
		  	icon.image = icon_url +"mm_20_purple.png";
		  	addIcon(icon);
		 }

		  // Make markers draggable
		  var marker = new GMarker(point, {icon:icon, draggable:true, bouncy:false, dragCrossMove:true});
		  map.addOverlay(marker);
		  marker.content = count;
		  markers.push(marker);
		  marker.tooltip = "Point "+ count;

		  GEvent.addListener(marker, "mouseover", function() {
		   showTooltip(marker);
		  });

		  GEvent.addListener(marker, "mouseout", function() {
		   tooltip.style.display = "none";
		 });

		  // Drag listener
		  GEvent.addListener(marker, "drag", function() {
		   tooltip.style.display= "none";
		   drawOverlay();
		  });

		// Drag listener
		  GEvent.addListener(marker, "dragend", function() 
		  {
		   if(markers.length > 2)
		   {
					// alert("Calling re-calculate");
					countMarkersInside();
		   }
		   
		   drawOverlay();
		  });

		  

		  // Second click listener
		  GEvent.addListener(marker, "click", function() {
		  tooltip.style.display = "none";

		  // Find out which marker to remove
		  for(var n = 0; n < markers.length; n++) {
		   if(markers[n] == marker) {
		    map.removeOverlay(markers[n]);
		    break;
		   }
		  }

		  // Shorten array of markers and adjust counter
		  markers.splice(n, 1);
		  if(markers.length == 0) {
		    count = 0;
		  }
		   else {
		    count = markers[markers.length-1].content;
		    drawOverlay();
		  }

		  if(markers.length > 2)
			{
				 alert("Calling re-calculate");
				countMarkersInside();
			}	
		  
		  });
		 drawOverlay();
		 }

	if(markers.length > 2)
	{
		// alert("Calling re-calculate");
		countMarkersInside();
	}
	return true;
}

function addIcon(icon) 
{ // Add icon attributes

	 icon.shadow= icon_url + "mm_20_shadow.png";
	 icon.iconSize = new GSize(12, 20);
	 icon.shadowSize = new GSize(22, 20);
	 icon.iconAnchor = new GPoint(6, 20);
	 icon.infoWindowAnchor = new GPoint(5, 1);
}


function showTooltip(marker) 
{ // Display tooltips

	 tooltip.innerHTML = marker.tooltip;
	 tooltip.style.display = "block";

	 // Tooltip transparency specially for IE
	 if(typeof(tooltip.style.filter) == "string") {
	 tooltip.style.filter = "alpha(opacity:70)";
	 }

	 var currtype = map.getCurrentMapType().getProjection();
	 var point= currtype.fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
	 var offset= currtype.fromLatLngToPixel(marker.getLatLng(),map.getZoom());
	 var anchor = marker.getIcon().iconAnchor;
	 var width = marker.getIcon().iconSize.width + 6;
	// var height = tooltip.clientHeight +18;
	 var height = 10;
	 var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width, offset.y - point.y -anchor.y - height)); 
	 pos.apply(tooltip);
}

function drawOverlay()
{

	 if(poly)
	 { 
		 map.removeOverlay(poly); 
	 }

	 points.length = 0;

	for(i = 0; i < markers.length; i++) 
	{
	  	points.push(markers[i].getLatLng());
	}
	 
	 // Polygon mode
	 points.push(markers[0].getLatLng());
	 //poly = new GPolygon(points, lineColor, lineWeight, lineOpacity, fillColor, fillOpacity);
	 poly = new GPolygon(points, "#000000", 1, 1, "#336699", 0.3);
	 map.addOverlay(poly);
}


function isInside(point) 
{
    var j=0;
    var oddNodes = false;
    var x = point.lng();
    var y = point.lat();
    for (var i=0; i < poly.getVertexCount(); i++) {
      j++;
      if (j == poly.getVertexCount()) {j = 0;}
      if (((poly.getVertex(i).lat() < y) && (poly.getVertex(j).lat() >= y))
      || ((poly.getVertex(j).lat() < y) && (poly.getVertex(i).lat() >= y))) {
        if ( poly.getVertex(i).lng() + (y - poly.getVertex(i).lat())
        /  (poly.getVertex(j).lat()-poly.getVertex(i).lat())
        *  (poly.getVertex(j).lng() - poly.getVertex(i).lng())<x ) {
          oddNodes = !oddNodes
        }
      }
    }
    return oddNodes;
  }


function countMarkersInside()
{
	//alert("first " + document.getElementById('selected_frames').innerHTML);
	var lHtmlStr = "<table border=0>";
	lHtmlStr += "<thead><tr><th>Check</th><th>Logo</th><th>Department Name</th><th>Emirate</th><th>Address</th><th>Description</th></tr></thead>"
	var lCount = 0;
	for(i = 0; i < g_marker_arr.length; i++) 
	{
		//alert("The marker " + i + " is inside - " + isInside(g_marker_arr[i].latLong));
		if(isInside(g_marker_arr[i].latLong) == true)
		{
			lHtmlStr += "<tr>" + "<td><input type=checkbox checked=true /></td>" + "<td><img src=" + g_marker_arr[i].logo_path + " /></td> " + "<td><font face=verdana color=blue size=2 >" +  g_marker_arr[i].department + "</font></td>" +  "<td><font face=verdana color=blue size=2 >" +  g_marker_arr[i].emirate + "</font></td>" + "<td><font face=verdana color=blue size=2 >" +  g_marker_arr[i].address + "</font></td>" + "<td><font face=verdana color=blue size=2 >" +  g_marker_arr[i].description + "</font></td>" +   "</tr>";
			lCount++;
			//alert("inside loop");
			//alert(lHtmlStr);
		}
	}
	//alert("exited loop");
	lHtmlStr += "</table>";
	document.getElementById('selected_frames').innerHTML = lHtmlStr;
	document.getElementById('numframes_selected').innerHTML = "Number of frames selected is " + lCount;
}

</script>






</head>

<body onload="load()" onunload="GUnload()" topmargin="0" leftmargin="0" >

<div class=box style="width: 680px; height:460px;">
<div id="map" style="position: relative;top: 5px; left: 5px;float:left;width: 670px; height:450px;border: 1px solid black;">
</div>
</div>


<!--   <div style="clear:both;"></div> -->

<div id="myscroll" style="position: absolute;float:left; top:0px; right:0px;">
<div class=box>
<table  border=0>
<tr><td><img src="/images/add.png"/>Add Frame</td></tr>
<!-- /* Get all the departments and their logo's */  -->
   <%
   List<CDepartment> lDeptList = CDepartmentFactory.getAllDepartments();
   out.print("<tr>");
   int lColumnSize =2;
   for( int lCount = 1; lCount <= lDeptList.size(); lCount++)
   {
	   boolean lIsSet = false;
	   CDepartment lDept = lDeptList.get(lCount-1);
	   /* TODO: Clean it up someday -  Stupid logic follows */
	   if( (lCount % lColumnSize ) == 0  ) 
	   {
		   lIsSet = true;
		   System.out.println("[true] Opened [" + lCount + "] <tr> ");
		   
	   }
	   
	   out.print("<td onClick=\"onBtnClick('" + lDept.getDepartmentName() + "')\"><img  id=\"" + lDept.getDepartmentName() + "\"" + " name=\"" + "1" + "\"" + " src=\"" + lDept.getLogo().getUrl() + " \">" + "<font size=1>" + lDept.getDepartmentName() +  "</font>" +  "</td>");
	   System.out.println("Department name is " + lDept.getDepartmentName() + " Url is " + lDept.getLogo().getUrl());
	   if( (lCount % lColumnSize ) == 0 ) 
	   {
		   if(lIsSet)
		   {
			   out.print("</tr>");
			   out.print("<tr>");
			   System.out.println("[true] Closed [" + lCount + "] </tr> ");
			   lIsSet = false;
		   }
		   
	   }
		   
	   
   }
   
   %> 
</table>
</div>
<div id="test" style="float:left;">
<div id="box1" class="box">
<table cellspacing="1">
<tr>
<td>
<font size=1>
<select id="dept_combo_box" onchange=getFramesForDepartment()>
<option>Select a Department</option>
<%
	for( int lCount = 0; lCount < lDeptList.size(); lCount++)
	{
		CDepartment lDept = lDeptList.get(lCount);
		out.print("<option value=\"" + lDept.getDepartmentName() + "\" >" + lDept.getDepartmentName() + " (" + lDept.getLocations().size()  + ")" +  "</option>");
	}
%>
</font>
<!--   <option value="6" >ANDHRA PRADESH</option> <option value="19" >ARUNACHAL PRADESH</option> <option value="21" >ASSAM</option> <option value="23" >BIHAR</option> <option value="25" >CHHATTISGARH</option> <option value="8" >GOA</option> <option value="9" >GUJARAT</option> <option value="31" >HARYANA</option> <option value="27" >HIMACHAL PRADESH</option> <option value="13" >JAMMU AND KASHMIR</option> <option value="26" >JHARKHAND</option> <option value="4" >KARNATAKA</option> <option value="5" >KERALA</option> <option value="14" >MADHYA PRADESH</option> <option value="10" >MAHARASHTRA</option> <option value="16" >MANIPUR</option> <option value="20" >MEGHALAYA</option> <option value="15" >MIZORAM</option> <option value="17" >NAGALAND</option> <option value="28" >ORISSA</option> <option value="32" >PUNJAB</option> <option value="12" >RAJASTHAN</option> <option value="7" >TAMIL NADU</option> <option value="18" >TRIPURA</option> <option value="30" >UTTAR PRADESH</option> <option value="29" >UTTARAKHAND</option> <option value="11" >WEST BENGAL</option> </select> </td> -->
</select> 
</td>
 </tr>
    <tr><td><input type="checkbox" name="showlocationsbox" id="showlocationsbox" value="ShowAllLocations"> Show All Locations.</td></tr>
    <tr><td><div id="frame_add_status"></div></td></tr>
    </table>
</div>
</div> 
</div>
<div style="clear:both;"></div>

</body>
</html>

